import React from 'react';
import {createStore, combineReducers, compose, applyMiddleware} from 'redux';
import {get} from 'axios';
import thunk from 'redux-thunk';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';


//redux中的三个重要部分：action>reducer>state（store）
const counterReducer = function (state = {count:1},action) {
  switch (action.type){
    case 'COUNT_ADD':
      return {
        ...state,count:state.count + 1
      }
    case 'COUNT_DEL':
      return {
        ...state,count:state.count - 2
      }
      default :
      return state
  }
}

const postReducer = function(state = {list:[{title:'你啊好'}]},action){
  switch (action.type){
    case 'LOAD_POSTS':
      return {
        ...state,
        list:action.payload
      }
      default :
        return state
  }
}
//通过combineReducers把多个reducer进行合并
const rootReducer = combineReducers({
  counter:counterReducer,
  posts:postReducer
})

const store = createStore(rootReducer,
  compose(
    applyMiddleware(...[thunk]),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  ),

  )


console.log(store)
console.log('1',store.getState())

//如果要改变一个reducer的值，需要使用dispatch派发一个action
//action需要两个参数
//  type  通过type区分对state做什么操作
//  payload 传递的值


store.dispatch({
  type:'COUNT_ADD',
  payload:{}
})

console.log(store)
console.log('2',store.getState())

store.dispatch({
  type:'COUNT_DEL',
  payload:{}
})
console.log(store)
console.log('3',store.getState())

const getPostRequest = () => {
  return get('http://jsonplaceholder.typicode.com/posts')
}
store.dispatch(async function(dispatch) {
  const res = await getPostRequest()
  console.log(res.data)
  dispatch({
    type:'LOAD_POSTS',
    payload:res.data
  })
})

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
